import {
  login
} from '@/api/auth';

export default {
  namespaced: true,
  state: {
    isShowLogin: true,

    token: undefined,
    id: undefined,
    info: {},
    permissions: [],

    currentRoleType: undefined,
  },
  mutations: {
    UPDATE_TOKEN(state, token) {
      state.token = token;
    },

    UPDATE_PERMISSIONS(state, permissions) {
      state.permissions = permissions;
    },

    UPDATE_ID(state, id) {
      state.id = id;
    },

    UPDATE_INFO(state, info) {
      state.info = info;
    },

    UPDATE_CURRENT_ROLE_TYPE(state, currentRoleType) {
      state.currentRoleType = currentRoleType;
    },

    UPDATE_SHOW_LOGIN(state, isShowLogin) {
      state.isShowLogin = isShowLogin;
    }

  },
  actions: {
    login({
      commit
    }, data) {
      return new Promise((resolve, reject) => {
        login({
          username: data.username,
          password: data.password,
          captcha: data.captcha,
          captchaId: data.captchaId
        }).then(res => {
          commit("UPDATE_ID", res.id);
          commit("UPDATE_PERMISSIONS", res.codes);
          commit("UPDATE_TOKEN", res.token);
          commit("UPDATE_INFO", res.info);
          resolve(res);
        }).catch(error => {
          reject(error);
        })
      })
    },

    setUserInfo({
      commit
    }, data) {
      commit("UPDATE_ID", data.id);
      commit("UPDATE_PERMISSIONS", data.codes);
      commit("UPDATE_TOKEN", data.token);
      commit("UPDATE_INFO", data.info);
    },

    logout({
      commit
    }) {
      return new Promise((resolve, reject) => {
        commit("UPDATE_TOKEN", undefined);
        commit("UPDATE_PERMISSIONS", undefined);
        commit("UPDATE_ID", undefined);
        commit("UPDATE_INFO", undefined);
        commit("UPDATE_CURRENT_ROLE_TYPE", undefined);
        resolve();
      })
    },

    currentRoleType({
      commit
    }, data) {
      return new Promise((resolve, reject) => {
        commit("UPDATE_CURRENT_ROLE_TYPE", data);
        resolve();
      })
    },

    setShowLogin({
      commit
    }, data) {
      commit('UPDATE_SHOW_LOGIN', data);
    },

  },
  getters: {
    token(state) {
      return state.token;
    },

    id(state) {
      return state.id;
    },

    info(state) {
      return state.info;
    },

    permissions(state) {
      return state.permissions;
    },

    currentRoleType(state) {
      return state.currentRoleType;
    },

    isShowLogin(state) {
      return state.isShowLogin;
    }
  }
}